<template>
  <view class="ai-assistant-page">
    <!-- 导航栏 -->
    <up-navbar :placeholder="true" left-icon="arrow-left" title="AI书法助手" bg-color="#f8f8f8" title-color="#333"
      @left-click="goBack"></up-navbar>

    <!-- 聊天容器 -->
    <scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" scroll-with-animation>
      <view class="chat-list">
        <!-- 欢迎消息 -->
        <view v-if="messageList.length === 0" class="welcome-message">
          <view class="welcome-card">
            <up-icon name="server-man" size="60" color="#4A90E2"></up-icon>
            <text class="welcome-title">欢迎使用AI书法助手</text>
            <text class="welcome-desc">我可以为您介绍书法作品、解答书法问题、推荐学习资源</text>
          </view>
        </view>

        <!-- 消息列表 -->
        <view v-for="(message, index) in messageList" :key="index" class="message-item">
          <!-- 用户消息 -->
          <view v-if="message.type === 'user'" class="user-message">
            <view class="message-content user-content">
              {{ message.content }}
            </view>
            <up-avatar :src="userAvatar" size="36"></up-avatar>
          </view>

          <!-- AI回复 -->
          <view v-else class="ai-message">
            <view class="ai-avatar">
              <up-icon name="server-man" size="24" color="#4A90E2"></up-icon>
            </view>
            <view class="message-content ai-content">
              <view v-if="message.loading" class="thinking-container">
                <view class="thinking-animation">
                  <view class="thinking-dot"></view>
                  <view class="thinking-dot"></view>
                  <view class="thinking-dot"></view>
                </view>
                <text class="thinking-text">AI助手正在思考中...</text>
              </view>
              <!-- 打字机效果显示AI回复 -->
              <text v-else class="typewriter">{{ message.displayContent || message.content }}</text>
            </view>
          </view>
        </view>

        <!-- 快捷问题（仅在没有消息时显示） -->
        <view v-if="messageList.length === 1" class="quick-questions">
          <text class="quick-title">快速开始</text>
          <view class="question-list">
            <view v-for="(item, index) in quickQuestions" :key="index" class="question-item"
              @click="sendQuickQuestion(item)">
              {{ item }}
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-container">
        <up-input v-model="inputText" placeholder="请输入您的问题..." :border="'none'" :clearable="true"
          @keyboardheightchange="handleKeyboard" class="message-input" @confirm="sendMessage">
        </up-input>

        <view class="send-btn" @click="sendMessage" :class="{ active: canSend }">
          <up-icon v-if="!isLoading" name="arrow-right" size="20" color="#fff"></up-icon>
          <up-loading-icon v-else color="#fff" size="16"></up-loading-icon>
        </view>
      </view>

      <!-- 功能按钮 -->
      <view class="function-buttons">
        <view class="function-btn" @click="clearHistory">
          <up-icon name="trash" size="18" color="#666"></up-icon>
          <text>清空记录</text>
        </view>

        <view class="function-btn" @click="shareConversation">
          <up-icon name="share" size="18" color="#666"></up-icon>
          <text>分享对话</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onUnmounted } from 'vue'
import alovaInstance from '@/api/core/alova.js'
import config from '../static/js/config.js'

// 响应式数据
const inputText = ref('')
const messageList = reactive([])
const scrollTop = ref(0)
const isLoading = ref(false)
const keyboardHeight = ref(0)
const isAiTyping = ref(false)
const conversationId = ref(null)

// 用户头像（可以从用户信息中获取）
const userAvatar = ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg')

// 快捷问题
const quickQuestions = reactive([
  '介绍一下王羲之的兰亭序',
  '书法初学者应该从哪里开始？',
  '如何选择合适的毛笔？',
  '楷书和行书有什么区别？'
])

// 计算属性
const canSend = computed(() => {
  return inputText.value.trim().length > 0 && !isLoading.value
})

// 方法
const goBack = () => {
  // 获取当前页面栈
  const pages = getCurrentPages();

  if (pages.length > 1) {
    // 如果有上一页，则正常返回
    uni.navigateBack({
      fail: (err) => {
        console.error('返回失败:', err);
        // 返回失败时跳转到首页
        uni.switchTab({
          url: '/pages/index/index'
        });
      }
    });
  } else {
    // 如果是第一页，跳转到首页
    uni.switchTab({
      url: '/pages/index/index'
    });
  }
};

const sendQuickQuestion = (question) => {
  inputText.value = question
  sendMessage()
}

const sendMessage = async () => {
  if (!canSend.value) return

  const message = inputText.value.trim()
  inputText.value = ''

  // 添加用户消息
  messageList.push({
    type: 'user',
    content: message,
    time: new Date()
  })

  // 添加AI加载消息
  const aiMessageIndex = messageList.push({
    type: 'ai',
    content: '',
    displayContent: '',
    loading: true,
    time: new Date()
  }) - 1

  isLoading.value = true
  isAiTyping.value = true
  scrollToBottom()

  try {
    // 调用Dify API（包含重试机制）
    const response = await callDifyAPIWithRetry(message, 3)

    // 更新AI回复
    const lastMessage = messageList[aiMessageIndex]
    if (lastMessage) {
      lastMessage.loading = false
      lastMessage.content = response

      // 启动打字机效果
      startTypewriterEffect(aiMessageIndex, response)

      // 更新对话ID
      if (response.conversation_id) {
        conversationId.value = response.conversation_id
      }
    }
  } catch (error) {
    console.error('Dify API调用失败:', error)
    // 错误处理
    const lastMessage = messageList[aiMessageIndex]
    if (lastMessage) {
      lastMessage.loading = false
      lastMessage.content = `抱歉，AI助手暂时无法回答您的问题: ${error.message || '请稍后再试'}`
      // 错误信息直接显示，不使用打字机效果
      lastMessage.displayContent = lastMessage.content
    }
  } finally {
    isLoading.value = false
    isAiTyping.value = false
    scrollToBottom()
  }
}

// 打字机效果实现
const startTypewriterEffect = (messageIndex, fullText) => {
  const message = messageList[messageIndex]
  if (!message) return

  // 重置显示内容
  message.displayContent = ''

  let currentIndex = 0
  const typingSpeed = 20 // 每个字符的间隔时间（毫秒）

  const typeNextCharacter = () => {
    if (currentIndex < fullText.length) {
      message.displayContent += fullText.charAt(currentIndex)
      currentIndex++

      // 滚动到底部以显示最新内容
      scrollToBottom()

      // 继续下一个字符
      setTimeout(typeNextCharacter, typingSpeed)
    }
  }

  // 开始打字效果
  typeNextCharacter()
}

// 调用Dify API（带重试机制）
const callDifyAPIWithRetry = async (message, maxRetries = 3) => {
  let lastError;

  for (let i = 0; i <= maxRetries; i++) {
    try {
      // 如果不是第一次尝试，添加延迟
      if (i > 0) {
        // 指数退避延迟（1秒, 2秒, 4秒...）
        await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000))
      }

      const response = await callDifyAPI(message)
      return response; // 成功则返回结果
    } catch (error) {
      lastError = error;
      console.warn(`API调用失败 (尝试 ${i + 1}/${maxRetries + 1}):`, error.message)

      // 如果是最后一次尝试，抛出错误
      if (i === maxRetries) {
        throw error;
      }
    }
  }
}

// 调用Dify API
const callDifyAPI = async (message) => {
  // 构造请求参数
  const payload = {
    inputs: {},
    query: message,
    response_mode: "blocking",
    conversation_id: conversationId.value,
    user: "user-db3cab4a" // 可以替换为实际用户ID
  }

  // 发送请求到Dify API（使用alova）
  const method = alovaInstance.Post(
    `${config.difyConfig.API_URL}/chat-messages`,
    payload,
    {
      // 设置请求头
      headers: {
        'Authorization': `Bearer ${config.difyConfig.API_KEY}`,
        'Content-Type': 'application/json'
      },
      // 为Dify API设置更长的超时时间
      timeout: 3000000
    }
  )
  
  const response = await method.send()

  // 处理响应
  if (response && response.answer) {
    return response.answer
  } else if (response && response.message) {
    return response.message
  } else {
    throw new Error('API响应格式错误')
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery()
    query.select('.chat-list').boundingClientRect(data => {
      if (data) {
        scrollTop.value = data.height
      }
    }).exec()
  })
}

const handleKeyboard = (e) => {
  keyboardHeight.value = e.height
}

const clearHistory = () => {
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有聊天记录吗？',
    success: (res) => {
      if (res.confirm) {
        messageList.splice(0)
        conversationId.value = null
        uni.showToast({ title: '已清空记录', icon: 'success' })
      }
    }
  })
}

const shareConversation = () => {
  if (messageList.length === 0) {
    uni.showToast({ title: '暂无对话记录', icon: 'none' })
    return
  }

  uni.showToast({ title: '分享功能开发中', icon: 'none' })
}

onMounted(() => {
  // 页面加载完成后的初始化
  // 添加欢迎消息
  setTimeout(() => {
    if (messageList.length === 0) {
      messageList.push({
        type: 'ai',
        content: '您好！我是您的专属AI书法助手，有什么我可以帮您的吗？',
        displayContent: '',
        time: new Date()
      })

      // 为欢迎消息启动打字机效果
      nextTick(() => {
        startTypewriterEffect(messageList.length - 1, '您好！我是您的专属AI书法助手，有什么我可以帮您的吗？')
        scrollToBottom()
      })
    }
  }, 500)
})

onUnmounted(() => {
  // 组件销毁时的清理工作
})
</script>

<style lang="scss" scoped>
.ai-assistant-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f6fa;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
}

.chat-list {
  min-height: 60vh;
  padding: 20rpx 20rpx;
  padding-bottom: 20rpx;
}

.welcome-message {
  .welcome-card {
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx 40rpx;
    text-align: center;
    margin-bottom: 40rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .welcome-title {
      display: block;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin: 30rpx 0 20rpx;
    }

    .welcome-desc {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}

.quick-questions {
  .quick-title {
    display: block;
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }

  .question-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;

    .question-item {
      background: #fff;
      border-radius: 16rpx;
      padding: 24rpx 30rpx;
      font-size: 28rpx;
      color: #4A90E2;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s;

      &:active {
        transform: scale(0.98);
        background: #f0f8ff;
      }
    }
  }
}

.message-item {
  margin-bottom: 30rpx;

  .user-message {
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    gap: 16rpx;

    .user-content {
      background: linear-gradient(135deg, #4A90E2, #357ABD);
      color: #fff;
      max-width: 520rpx;
      border-radius: 20rpx 8rpx 8rpx 20rpx;
      padding: 24rpx 30rpx;
      font-size: 28rpx;
      line-height: 1.5;
      word-wrap: break-word;
      box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.2);
    }
  }

  .ai-message {
    display: flex;
    align-items: flex-start;
    gap: 16rpx;

    .ai-avatar {
      width: 72rpx;
      height: 72rpx;
      background: linear-gradient(135deg, #f0f8ff, #e6f2ff);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      border: 2rpx solid #e1eeff;
    }

    .ai-content {
      background: linear-gradient(135deg, #ffffff, #f8fbff);
      color: #333;
      max-width: 520rpx;
      border-radius: 8rpx 20rpx 20rpx 8rpx;
      padding: 10rpx 10rpx;
      font-size: 28rpx;
      line-height: 1.6;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
      border: 1rpx solid #f0f8ff;

      .thinking-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx 0;

        .thinking-animation {
          display: flex;
          gap: 12rpx;
          margin-bottom: 10rpx;

          .thinking-dot {
            width: 16rpx;
            height: 16rpx;
            background: linear-gradient(135deg, #4A90E2, #357ABD);
            border-radius: 50%;
            animation: thinking 1.8s infinite ease-in-out;

            &:nth-child(1) {
              animation-delay: -0.36s;
            }

            &:nth-child(2) {
              animation-delay: -0.18s;
            }
          }
        }

        .thinking-text {
          font-size: 26rpx;
          color: #666;
          font-style: italic;
        }
      }

      .loading-dots {
        display: flex;
        gap: 8rpx;
        padding: 10rpx 0;

        .dot {
          width: 12rpx;
          height: 12rpx;
          background: linear-gradient(135deg, #4A90E2, #357ABD);
          border-radius: 50%;
          animation: loading 1.4s infinite ease-in-out;

          &:nth-child(1) {
            animation-delay: -0.32s;
          }

          &:nth-child(2) {
            animation-delay: -0.16s;
          }
        }
      }

      .typewriter {
        white-space: pre-wrap;
        word-wrap: break-word;
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      }
    }
  }
}

@keyframes thinking {

  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.6;
  }

  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

.input-area {
  background: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;

  .input-container {
    display: flex;
    align-items: center;
    background: #f5f6fa;
    border-radius: 50rpx;
    padding: 12rpx 20rpx;
    margin-bottom: 20rpx;

    .message-input {
      flex: 1;
      font-size: 28rpx;
    }

    .send-btn {
      width: 64rpx;
      height: 64rpx;
      background: #ccc;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
      margin-left: 16rpx;

      &.active {
        background: #4A90E2;
        transform: scale(1.05);
      }
    }
  }

  .function-buttons {
    display: flex;
    gap: 40rpx;

    .function-btn {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 16rpx 20rpx;
      border-radius: 12rpx;
      background: #f5f6fa;
      transition: all 0.3s;

      text {
        font-size: 24rpx;
        color: #666;
      }

      &:active {
        background: #e6e8eb;
      }
    }
  }
}

@keyframes thinking {

  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }

  40% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes typing {

  0%,
  80%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-10rpx);
  }
}
</style>
